package com.xing.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xing.reggie.common.BaseContext;
import com.xing.reggie.common.R;
import com.xing.reggie.entity.User;
import com.xing.reggie.service.UserService;
import com.xing.reggie.utils.SMSUtils;
import com.xing.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.xing.reggie.config.RedisConfig.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1.获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //2.生成4位的短信验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code:{}",code);
            //3.调用阿里云Api，发送短信验证码
//            SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //4.需要将验证码保存起来，放在session
//            session.setAttribute(phone,code);
            //将验证码存在在Redis中，设置超时时间5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

//            System.out.println("session--->"+session.getAttribute(phone));
            return R.success("手机短信验证码发送成功！");

        }else {
            return R.error("手机短信验证码发送失败");
        }

    }

    /**
     * 移动端用户登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取登录用户手机号
        String phone = map.get("phone").toString();
        //获取登录用户验证码
        String code = map.get("code").toString();

        //从session中得到保存的手机号对应的验证码
//        String sessionCode = (String) session.getAttribute(phone);

        //从Redis中获取验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        System.out.println("redis中验证码code="+code);
        //比较验证码是否一致，若相同，登录成功！
        if (sessionCode != null && sessionCode.equals(code)) {
            //判断登录用户手机号是否为新用户，如果是新用户则自动注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            //添加条件
            queryWrapper.eq(User::getPhone, phone);
            //查询
            User user = userService.getOne(queryWrapper);
            //判断
            if (user == null) {
                //新用户直接自动注册
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //如果用户登录成功，删除验证码！
            redisTemplate.delete(phone);

            return R.success(user);
        }else {
            return R.error("登陆失败");

        }

    }

    /**
     * 移动端用户退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清除session
       request.getSession().removeAttribute("user");

        return R.success("退出登录！");
    }
}
